package com.suning.sawp.in.controller.model;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.ExportConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.OrgInfo;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.oss.ExportTaskDto;
import com.suning.sawp.dto.precharge.CommonRtn;
import com.suning.sawp.exception.SawpException;
import com.suning.sawp.in.controller.DjBaseController;
import com.suning.sawp.in.controller.MyGsonView;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.intf.model.ModelCateBrand;
import com.suning.sawp.intf.model.ModelConstant;
import com.suning.sawp.intf.model.ModelErrorConstant;
import com.suning.sawp.intf.model.ModelManageService;
import com.suning.sawp.intf.model.ModelTaskAssignVo;
import com.suning.sawp.intf.model.ModelTaskBean;
import com.suning.sawp.intf.model.ModelTaskHasAssignVo;
import com.suning.sawp.intf.model.ModelTaskInfoVo;
import com.suning.sawp.intf.model.ModelTaskMonitorVo;
import com.suning.sawp.intf.model.ModelTaskNoAssignVo;
import com.suning.sawp.intf.model.OrgTreeBean;
import com.suning.sawp.intf.model.SaveTaskParam;
import com.suning.sawp.intf.model.TaskDetailBean;
import com.suning.sawp.service.impl.model.ModelManageServiceImpl;
import com.suning.sawp.service.util.DJStringUtils;

@RequestMapping("/adminPage/model")
@Controller
public class ModelTaskController extends DjBaseController {

    @Resource
    ModelManageService          modelManageService;
    
    @Resource
    MongoTemplate mongoTemplate;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);
    
    /**
     * 总部
     */
    public static final String HQ_LEVEL = "0";
    /**
     * 大区
     */
    public static final String REGION_LEVEL = "1";
    /**
     * 分公司
     */
    public static final String COMPANY_LEVEL = "2";

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 
     * @param taskType
     * @param taskStartTime
     * @param taskEndTime
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryTask.do")
    public MyGsonView queryTask(String taskStartTime, String taskEndTime,
            Integer pageSize, Integer pageNo, String taskStatus) {
        ReturnMsg<QueryResult<ModelTaskBean>> ret = new ReturnMsg<QueryResult<ModelTaskBean>>();
        try {
            @SuppressWarnings("serial")
            Set<Integer> taskType = new HashSet<Integer>(){{
                add(ModelConstant.TASK_TYPE_HQ);
                add(ModelConstant.TASK_TYPE_REGION);
            }};
            ret = modelManageService.queryTaskList(taskStartTime, taskEndTime, taskType, pageNo,
                    pageSize, taskStatus);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("查询任务列表异常,开始时间:%s,结束时间:%s", taskStartTime,
                    taskEndTime), e);
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: 查询所有品类<br>
     * 〈功能详细描述〉
     * 
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryCateBrand.do")
    public MyGsonView queryCateBrand() {
        ReturnMsg<List<ModelCateBrand>> ret = new ReturnMsg<List<ModelCateBrand>>();
        try {
            ret = modelManageService.queryBrandCate();
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("ModelTaskController queryCateBrand error", e);
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述:查询组织树<br>
     * 〈功能详细描述〉
     * 
     * @param storeType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryOrgTree.do")
    public MyGsonView queryOrgTree(Integer storeType,Long taskId) {
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        String regionCode = null;
        String branchCode = null;
        String storeCode = null;
        if (OrgInfo.ORG_LEVEL.COMPANY_LEVEL.equals(employeeInfo.getOrgLevel())) {
            branchCode = employeeInfo.getBranchCode();
        } else if (OrgInfo.ORG_LEVEL.STORE_LEVEL.equals(employeeInfo.getOrgLevel())) {
            storeCode = employeeInfo.getStoreCode();
        } else if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
            regionCode = employeeInfo.getRegionCode();
        }
        ReturnMsg<List<OrgTreeBean>> ret = new ReturnMsg<List<OrgTreeBean>>();
        try {
            ret = modelManageService.queryOrgList(regionCode, branchCode, storeCode, storeType,taskId);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("ModelTaskController queryOrgTree error", e);
        }
        return setGsonView(ret);
    }
    
    /**
     * 查询任务品类，品牌
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param cateCode
     * @param taskId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryTaskCateBrands.do")
    public MyGsonView queryTaskCateBrands(Long taskId) {
        LOGGER.info("queryTaskCateBrands enter,taskId={}", taskId);
        ReturnMsg<List<ModelCateBrand>> ret = new ReturnMsg<List<ModelCateBrand>>();
        if (null == taskId) {
            LOGGER.warn("queryTaskCateBrands taskId is null");
            ret.setError(ErrorCodeConstants.ERR_0003, "taskId");
        } else {
            try {
                List<ModelCateBrand> list = modelManageService.queryTaskCateBrands(taskId);
                ret.setData(list);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error("ModelTaskController queryTaskCateBrands error", e);
            }
        }
        LOGGER.info("queryTaskCateBrands exit,taskId={}", taskId);
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: 查询未分配任务列表<br>
     * 〈功能详细描述〉
     * 
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryNoAssignList.do")
    public MyGsonView queryUnassignList(String branchCode, String regionCode, String storeCode, String cateCode,
            Integer pageNo, Integer pageSize, Long taskId, String taskStatus) {
        ReturnMsg<QueryResult<ModelTaskNoAssignVo>> ret = new ReturnMsg<QueryResult<ModelTaskNoAssignVo>>();
        if (null == taskId) {
            LOGGER.warn("queryTaskCateBrands taskId is null");
            ret.setError(ErrorCodeConstants.ERR_0003, (Object)"taskId");
        } else {
            try {
                ret = modelManageService.queryModelTaskNoAssign(regionCode, branchCode, storeCode,
                        DJStringUtils.initPageSize(pageSize), DJStringUtils.initPageNo(pageNo), taskId, taskStatus, cateCode);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error(
                        String.format(
                                "ModelTaskController queryOrgTree error queryParam(branchCode:%s,regionCode:%s,storeCode:%s",
                                branchCode, regionCode, storeCode), e);
            }
        }
        return setGsonView(ret);
    }
    
    
    /**
     * 查询已分配任务列表
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param branchCode
     * @param regionCode
     * @param storeCode
     * @param pageNo
     * @param pageSize
     * @param taskId
     * @param taskStatus
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryHasAssignList.do")
    public MyGsonView queryHasAssignList(String branchCode, String regionCode, String storeCode,
            Integer pageNo, Integer pageSize, Long taskId, String taskStatus, String cateCode, String brandCode) {
        ReturnMsg<QueryResult<ModelTaskHasAssignVo>> ret = new ReturnMsg<QueryResult<ModelTaskHasAssignVo>>();
        if (null == taskId) {
            LOGGER.warn("queryTaskCateBrands taskId is null");
            ret.setError(ErrorCodeConstants.ERR_0003, (Object)"taskId");
        } else {
            try {
                ret = modelManageService.queryModelTaskHasAssign(regionCode, branchCode, storeCode,
                        DJStringUtils.initPageSize(pageSize), DJStringUtils.initPageNo(pageNo), taskId, taskStatus, cateCode, brandCode);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error(
                        String.format(
                                "ModelTaskController queryOrgTree error queryParam(branchCode:%s,regionCode:%s,storeCode:%s",
                                branchCode, regionCode, storeCode), e);
            }
        }
        return setGsonView(ret);
    }
    
    
    /**
     *
     * @param branchCode
     * @param regionCode
     * @param storeCode
     * @param pageNo
     * @param pageSize
     * @param taskId
     * @param taskStatus 盘点状态 0未提交 1已提交
     * @param assignStatus  分配状态 0未分配 1已分配
     * @param cateCode
     * @param brandCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryAssignAllList.do")
    public MyGsonView queryAssignAllList(String branchCode, String regionCode, String storeCode,
            Integer pageNo, Integer pageSize, Long taskId, String taskStatus, String assignStatus, String cateCode, String brandCode) {
        ReturnMsg<QueryResult<ModelTaskAssignVo>> ret = new ReturnMsg<QueryResult<ModelTaskAssignVo>>();
        if (StringUtils.isBlank(regionCode) || null == taskId) {
            LOGGER.error("queryAssignAllList taskId is null");
            ret.setError(ErrorCodeConstants.ERR_0003, (Object)"taskId");
        } else {
            try {
                ret = modelManageService.queryAssignAllList(regionCode, branchCode, storeCode,
                        DJStringUtils.initPageSize(pageSize), DJStringUtils.initPageNo(pageNo), taskId, taskStatus,assignStatus, cateCode, brandCode);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error(
                        String.format(
                                "ModelTaskController queryAssignAllList error queryParam(branchCode:%s,regionCode:%s,storeCode:%s",
                                branchCode, regionCode, storeCode), e);
            }
        }
        return setGsonView(ret);
    }
    
    @RequestMapping("/queryTaskInfoByID.do")
    public MyGsonView queryTaskInfoByID(Long taskId) {
        ReturnMsg<ModelTaskInfoVo> ret = new ReturnMsg<ModelTaskInfoVo>();
        if (null == taskId) {
            LOGGER.warn("queryTaskInfoByID taskId is null");
            ret.setError(ErrorCodeConstants.ERR_0003, (Object)"taskId");
        } else {
            try {
                ret = modelManageService.queryTaskInfoByID(taskId);
                ModelTaskInfoVo resultData = ret.getData();
                EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
                
                if (OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(employeeInfo.getOrgLevel())) {
                    resultData.setCurrLevel(OrgInfo.ORG_LEVEL.HQ_LEVEL);
                    resultData.setRegionCode("");
                    resultData.setBranchCode("");
                }else if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
                    resultData.setCurrLevel(REGION_LEVEL);
                    resultData.setRegionCode(employeeInfo.getRegionCode());
                    resultData.setBranchCode("");
                }else  if (OrgInfo.ORG_LEVEL.COMPANY_LEVEL.equals(employeeInfo.getOrgLevel())) {
                    resultData.setCurrLevel(COMPANY_LEVEL);
                    resultData.setRegionCode(employeeInfo.getRegionCode());
                    resultData.setBranchCode(employeeInfo.getBranchCode());
                }
                ret.setData(resultData);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error( "ModelTaskController queryTaskInfoByID error queryParam,taskId:"+taskId+"", e);
            }
        }
        return setGsonView(ret);
    }
    
    @RequestMapping("/queryTaskMonitor.do")
    public MyGsonView queryTaskMonitor(String branchCode, String regionCode,Long taskId,Integer pageNo, Integer pageSize) {
        ReturnMsg<ModelTaskMonitorVo> ret = new ReturnMsg<ModelTaskMonitorVo>();
        LOGGER.info("queryTaskMonitor,branchCode:{},regionCode:{},taskId:{]",branchCode,regionCode,taskId);
        if (null == taskId) {
            LOGGER.warn("queryTaskMonitor taskId is null");
            ret.setError(ErrorCodeConstants.ERR_0003, (Object)"taskId");
        } else {
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
                if(StringUtils.isBlank(regionCode)){
                    regionCode = employeeInfo.getRegionCode();
                }
            }else  if (OrgInfo.ORG_LEVEL.COMPANY_LEVEL.equals(employeeInfo.getOrgLevel())) {
                if(StringUtils.isBlank(branchCode) ){
                    branchCode = employeeInfo.getBranchCode();
                }
            }
            
            try {
                ret = modelManageService.queryTaskMonitor(branchCode, regionCode,taskId, DJStringUtils.initPageSize(pageSize), DJStringUtils.initPageNo(pageNo));
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error( "ModelTaskController queryTaskMonitor error queryParam,taskId:"+taskId+"", e);
            }
        }
        return setGsonView(ret);
    }
    
    /**
     * 
     * 功能描述: 保存任务<br>
     * 〈功能详细描述〉
     *
     * @param brandList
     * @param endTime
     * @param startTime
     * @param storage
     * @param storeList
     * @param taskId
     * @param taskType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/saveTask.do")
    public MyGsonView saveTask(@RequestBody SaveTaskParam param){
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
        try{
            // 默认任务类型为总部任务
            param.setTaskType(1);
            if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
                // 大区员工创建的标记为大区任务
                param.setTaskType(2);
            }
            ret = modelManageService.saveTask(param.getStoreList(), param.getBrandList(), param.getStartTime(), param.getEndTime(), param.getStorage(), param.getTaskType(), employeeInfo.getStaffId(), param.getTaskId());
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(
                    String.format(
                            "ModelTaskController saveTask error param(%s)",
                            param.toString()), e);
        }
        return setGsonView(ret);
    }
    /**
     * 
     * 功能描述: 删除任务<br>
     * 〈功能详细描述〉
     *
     * @param taskId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/delTask.do")
    public MyGsonView deleteTask(Long taskId){
        ReturnMsg<CommonRtn> ret = new  ReturnMsg<CommonRtn>();
        try{
            ret = modelManageService.deleteTask(taskId);
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelTaskController deleteTask error taskId:%s",taskId),e);
        }
        return setGsonView(ret);
    }
    /**
     * 
     * 功能描述: 启用/禁用 任务<br>
     * 〈功能详细描述〉
     *
     * @param taskId
     * @param operateType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/validTask.do")
    public MyGsonView validTask(Long taskId,Integer operateType){
        ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
        try{
            ret = modelManageService.validTask(taskId, operateType);
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelTaskController validTask error taskId:%s",taskId),e);
        }
        return setGsonView(ret);
    }
    /**
     * 
     * 功能描述: 查询任务详情<br>
     * 〈功能详细描述〉
     *
     * @param taskId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryTaskInfo.do")
    public MyGsonView queryTaskDetail(Long taskId){
        ReturnMsg<TaskDetailBean> ret = new ReturnMsg<TaskDetailBean>();
        try{
            ret = modelManageService.queryTaskDetail(taskId);
        }catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("ModelTaskController queryTaskDetail error taskId:%s",taskId),e);
        }
        return setGsonView(ret);
    }
    
    /**
     * 
     * 功能描述: 未分配任务统计导出<br>
     * 〈功能详细描述〉
     *
     * @param regionCode
     * @param branchCode
     * @param storeCode
     * @param taskId
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportUnassign.do")
    public void exptUnassignTask(String regionCode,String branchCode,String storeCode,Long taskId, String cateCode, Integer index,HttpServletResponse response){
        OutputStream ouputStream = null;
        try {
        if(StringUtils.isBlank(regionCode) || index == null || taskId == null){
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            ouputStream = response.getOutputStream();
            ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001).getBytes());
        }else{
            Workbook workbook = modelManageService.exportUnassignTask(branchCode, storeCode, regionCode, cateCode, taskId, index);
            if(workbook == null){
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                ouputStream = response.getOutputStream();
                ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E007).getBytes());
            }else{
                response.setContentType("application/x-download");
                response.setHeader("Content-disposition", "attachment;filename=noAssignTask_" + index + ".xlsx");    
                ouputStream = response.getOutputStream();
                workbook.write(ouputStream);
            }
        }
        ouputStream.flush();    
        ouputStream.close();
        } catch (Exception e) {
            LOGGER.error("exptUnassignTask 导出excel出错", e);
        }finally{
            modelManageService.endExportExcel();
        }
    }
    
    /**
     * 
     * 功能描述: 未分配任务统计导出<br>
     * 〈功能详细描述〉
     *
     * @param regionCode
     * @param branchCode
     * @param storeCode
     * @param taskId
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportUnassignEx.do")
    public MyGsonView exptUnassignTaskEx(String regionCode,String branchCode,String storeCode,Long taskId, String cateCode, Integer index,HttpServletResponse response){
        ReturnMsg<Integer> ret = new ReturnMsg<Integer>();
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        if(StringUtils.isBlank(regionCode) || index == null || taskId == null){
            LOGGER.error("exptUnassignTaskEx.Paramter is null.regionCode:{}, index:{}, taskId:{}", regionCode, index, taskId);
            ret.setError(ModelErrorConstant.MODEL_ERR_E001,
                    ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001));
        
        } else if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
            LOGGER.error("exptUnassignTaskEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
            ret.setError(ModelErrorConstant.MODEL_ERR_E001,
                    ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001));
        } else {
            String staffId = employeeInfo.getStaffId();
            String className = ModelManageServiceImpl.class.getName();
            String methodName = ExportConstants.ExportMethodName.EXPORT_UNASSIGN_TASK_EX;
            @SuppressWarnings("unchecked")
            List<Object> params = new ArrayList<Object>(Arrays.asList(staffId, branchCode, storeCode, regionCode,
                    cateCode, taskId, index));
            List<String> paramsType = new ArrayList<String>(Arrays.asList(String.class.getName(),
                    String.class.getName(), String.class.getName(), String.class.getName(), String.class.getName(),
                    Long.class.getName(), Integer.class.getName()));
            ExportTaskDto dto = new ExportTaskDto(staffId, className, methodName, params, paramsType);
            mongoTemplate.save(dto);
        }
        
        return setGsonView(ret);
    }
    
    /**
     * 导出已分配的任务文件
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param regionCode
     * @param branchCode
     * @param storeCode
     * @param cateCode
     * @param brandCode
     * @param taskStatus
     * @param taskId
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportHasAssign.do")
    public void exptHasAssignTask(String regionCode,String branchCode,String storeCode, String cateCode, String brandCode, String taskStatus, Long taskId, Integer index, HttpServletResponse response){
        OutputStream ouputStream = null;
        try {
        if(StringUtils.isBlank(regionCode) || index == null || taskId == null){
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            ouputStream = response.getOutputStream();
            ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001).getBytes());
        }else{
            Workbook workbook = modelManageService.exportHasAssignTask(taskId, regionCode, branchCode, storeCode, cateCode, brandCode, taskStatus, index);
            if(workbook == null){
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                ouputStream = response.getOutputStream();
                ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E007).getBytes());
            }else{
                response.setContentType("application/x-download");
                response.setHeader("Content-disposition", "attachment;filename=hasAssignTask_" + index + ".xlsx");    
                ouputStream = response.getOutputStream();
                workbook.write(ouputStream);
            }
        }
        ouputStream.flush();    
        ouputStream.close();
        } catch (Exception e) {
            LOGGER.error("exptUnassignTask 导出excel出错", e);
        }finally{
            modelManageService.endExportExcel();
        }
    }
    
    @RequestMapping("/exportAssign.do")
    public void exportAssign(String regionCode,String branchCode,String storeCode, String cateCode, String brandCode, String taskStatus, 
            String assignStatus,Long taskId, Integer index, HttpServletResponse response) throws IOException{
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();

        OutputStream ouputStream = null;
        try {
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");            
            ouputStream = response.getOutputStream();
            if (StringUtils.isBlank(regionCode) ||   null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())|| taskId == null || index == null) {
                LOGGER.error("exportAssign.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.ERR_E001).getBytes());
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelManageServiceImpl.class.getName(); 
                String methodName = ExportConstants.ExportMethodName.EXPORT_EXCEL_MODEL_TASK;
                @SuppressWarnings("unchecked")
                List<Object> params =  new ArrayList<Object>(Arrays.asList(staffId, regionCode, branchCode, storeCode, cateCode,brandCode,taskStatus,assignStatus ,taskId,index));
                List<String> paramsType = new ArrayList<String>(Arrays.asList(String.class.getName(), String.class.getName(),String.class.getName(), String.class.getName(),String.class.getName(), String.class.getName(),
                        String.class.getName(), String.class.getName(), Long.class.getName(), Integer.class.getName()));
                ExportTaskDto dto = new ExportTaskDto(staffId, className, methodName, params, paramsType);
                mongoTemplate.save(dto);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (IOException e) {
            LOGGER.error("exportAssign 导出excel出错", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        }finally{
            if(ouputStream!=null){
                ouputStream.flush();    
                ouputStream.close();
            }
        }
    }
    
    @RequestMapping("/exportMonitor.do")
    public void exportMonitor(String branchCode, String regionCode,Long taskId, HttpServletResponse response) throws IOException{
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        OutputStream ouputStream = null;
        try {
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");            
            ouputStream = response.getOutputStream();
            if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())|| taskId == null) {
                LOGGER.error("exportMonitor.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.ERR_E001).getBytes());
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelManageServiceImpl.class.getName(); 
                String methodName = ExportConstants.ExportMethodName.EXPORT_EXCEL_MODEL_MONITOR;
                @SuppressWarnings("unchecked")
                List<Object> params =  new ArrayList<Object>(Arrays.asList(staffId, regionCode, branchCode, taskId));
                List<String> paramsType = new ArrayList<String>(Arrays.asList(String.class.getName(), String.class.getName(),String.class.getName(), Long.class.getName()));
                ExportTaskDto dto = new ExportTaskDto(staffId, className, methodName, params, paramsType);
                mongoTemplate.save(dto);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (IOException e) {
            LOGGER.error("exportMonitor 导出excel出错", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        }finally{
            if(ouputStream!=null){
                ouputStream.flush();    
                ouputStream.close();
            }
        }
    }
    
    /**
     * 导出已分配的任务文件
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param regionCode
     * @param branchCode
     * @param storeCode
     * @param cateCode
     * @param brandCode
     * @param taskStatus
     * @param taskId
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportHasAssignEx.do")
    public MyGsonView exptHasAssignTaskEx(String regionCode, String branchCode, String storeCode, String cateCode,
            String brandCode, String taskStatus, Long taskId, Integer index, HttpServletResponse response) {
        ReturnMsg<Integer> ret = new ReturnMsg<Integer>();
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        if (StringUtils.isBlank(regionCode) || index == null || taskId == null) {
            LOGGER.error("exptHasAssignTaskEx.Paramter is null.regionCode:{}, index:{}, taskId:{}", regionCode, index,
                    taskId);
            ret.setError(ModelErrorConstant.MODEL_ERR_E001,
                    ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001));
        } else if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
            LOGGER.error("exptHasAssignTaskEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
            ret.setError(ModelErrorConstant.MODEL_ERR_E001,
                    ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001));
        } else {
            String staffId = employeeInfo.getStaffId();
            String className = ModelManageServiceImpl.class.getName();
            String methodName = ExportConstants.ExportMethodName.EXPORT_HASASSIGN_TASK_EX;
            @SuppressWarnings("unchecked")
            List<Object> params = new ArrayList<Object>(Arrays.asList(staffId, taskId, regionCode, branchCode,
                    storeCode, cateCode, brandCode, taskStatus, index));
            List<String> paramsType = new ArrayList<String>(Arrays.asList(String.class.getName(), Long.class.getName(),
                    String.class.getName(), String.class.getName(), String.class.getName(), String.class.getName(),
                    String.class.getName(), String.class.getName(), Integer.class.getName()));
            ExportTaskDto dto = new ExportTaskDto(staffId, className, methodName, params, paramsType);
            mongoTemplate.save(dto);
        }
        

        return setGsonView(ret);
    }
    
    /**
     * 查询指定督导任务列表
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param staffId
     * @param pageNo
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryAppointTask.do")
    public MyGsonView queryAppointTask(String staffId, Integer pageNo, Integer pageSize) {
        ReturnMsg<QueryResult<ModelTaskNoAssignVo>> ret = new ReturnMsg<QueryResult<ModelTaskNoAssignVo>>();
        if (StringUtils.isBlank(staffId)) {
            LOGGER.warn("queryAppointTask staffId is null");
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, "入参staffId必填");
        } else {
            try {
                ret = modelManageService.queryAppointTask(staffId,DJStringUtils.initCurrIndex(pageNo, pageSize),
                        DJStringUtils.initPageSize(pageSize));
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error("queryAppointTask staffId=" + staffId, e);
            }
        }
        return setGsonView(ret);
    }
    
    /**
     * 删除指定督导任务数据
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param staffId
     * @param taskId
     * @param storeCode
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/clearAppointTask.do")
    public MyGsonView clearAppointTask(String staffId, Long taskId, String storeCode, String cateCode) {
        ReturnMsg<String> ret = new ReturnMsg<String>();
        if (null == taskId || taskId < 1) {
            LOGGER.warn("clearAppointTask taskId is null");
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, "入参taskId必填");
        } else if (StringUtils.isBlank(staffId)) {
            LOGGER.warn("clearAppointTask staffId is null");
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, "入参staffId必填");
        } else if (StringUtils.isBlank(storeCode)) {
            LOGGER.warn("clearAppointTask storeCode is null");
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, "入参storeCode必填");
        } else if (StringUtils.isBlank(cateCode)) {
            LOGGER.warn("clearAppointTask cateCode is null");
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, "入参cateCode必填");
        } else {
            try {
                modelManageService.clearAppointTask(taskId, staffId, storeCode, cateCode);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error("queryAppointTask staffId=" + staffId, e);
            }
        }
        return setGsonView(ret);
    }
}
